/*
 * Copyright (c) 2012 RTCLab
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification, are
 * permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice, this list of
 *    conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright notice, this list
 *    of conditions and the following disclaimer in the documentation and/or other materials
 *    provided with the distribution.
 *
 */

import flash.external.*;
import com.rtckit.*;

private var softphones:Array;

private var params:Object;

private function writeMessage(msg:String, level:String):void {
	if (params.onMessage)
		ExternalInterface.call(params.onMessage, {text: msg, level: level});
}

public function appComplete(event:Event):void {
	params = this.loaderInfo.parameters;
	softphones = new Array();
	ExternalInterface.addCallback("start", start);
	Logger.writeMessage = writeMessage;
	Logger.info('ready');
}

private function startImpl(threads:Number, config:SoftphoneConfig):void {
	var softphone:Softphone = new Softphone(config);
	if (params.random_username)
		params.username = 'rtckit_' + (Math.floor(Math.random() * 10000) + 1).toString();
	softphone.setAutoReg(params);
	if (params.number != '-')
		softphone.setAutoCall(params.number);
	softphone.connect(SoftphoneConfig.makeURL(params.gateway));
	softphones.push(softphone);
	
	threads--;
	if (threads > 0)
		setTimeout(startImpl, 50, threads, config);
}

private function start(auth:Object):void {
	params.auth = auth;
	var config:SoftphoneConfig = new SoftphoneConfig(params);
	config.stresstest = true;
	var threads:Number = new Number(params.threads);
	startImpl(threads, config);
}
